package com.clp.protocol.iec104.apdu;

import com.clp.protocol.iec104.apdu.apci.IApci;
import com.clp.protocol.iec104.apdu.asdu.IAsdu;
import com.clp.protocol.iec104.definition.ApduType;
import com.clp.protocol.iec104.definition.ConstVal;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.Objects;

/**
 * I帧
 */
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class IApdu implements Apdu {
    private IApci iApci;
    private IAsdu iAsdu;

    @Override
    public IApdu initBy(ByteBuf buf) {
        this.iApci = new IApci().initBy(buf);
        this.iAsdu = new IAsdu().initBy(buf);
        return this;
    }

    @Override
    public boolean isValid() {
        return iApci != null && iApci.isValid() && iAsdu != null && iAsdu.isValid();
    }

    @Override
    public void writeTo(ByteBuf buf) {
        iApci.writeTo(buf);
        iAsdu.writeTo(buf);
        // 注意：最后要设置长度
        buf.setByte(buf.readerIndex() + 1, buf.readableBytes() - ConstVal.HEAD_LEN - ConstVal.LENGTH_LEN);
    }

    @Override
    public ApduType apduType() {
        return ApduType.IType;
    }

    @Override
    public String toString() {
        switch (printOption) {
            case DESCRIPTION:
                return "     <帧类型：" + apduType().getDesc() + "> " + iApci + iAsdu;
            case HEX_STRING:
                return toHexString();
        }
        return null;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        IApdu iApdu = (IApdu) o;
        return Objects.equals(iApci, iApdu.iApci) && Objects.equals(iAsdu, iApdu.iAsdu);
    }

    @Override
    public int hashCode() {
        return Objects.hash(iApci, iAsdu);
    }
}

